import { Component, OnInit } from '@angular/core';
import { NetService } from './../../services/net.service';

interface Menu {
  _id: string;
  name: string;
  icon: string;
  code: string;
  link: string;
  parentId: string;
  roles: Array<string>;
}
@Component({
  selector: 'app-nav-bar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
  isCollapsed = true;
  menuData = [];
  treeData = [];
  constructor(private net: NetService) {
  }

  toggleFn(open: boolean) {
    this.isCollapsed = open;
  }

  // 递归处理菜单数据
  handleMenu(menus: Array<Menu>, parentId: string = '') {
    if (!menus || menus.length === 0) { return []; }
    const levelMenus = [];
    const nextLevelMenus = [];
    menus.forEach(item => {
      if (item.parentId === parentId) {
        levelMenus.push(item);
      } else {
        nextLevelMenus.push(item);
      }
    });
    const newMenu = [];
    levelMenus.forEach(item => {
      newMenu.push({
        key: item._id,
        title: item.name,
        icon: item.icon ? item.icon : '',
        code: item.code,
        link: item.link,
        roles: item.roles,
        parentId: item.parentId,
        isLeaf: nextLevelMenus.length === 0,
        children: this.handleMenu(nextLevelMenus, item._id)
      });
    });
    return newMenu;
  }

  // 获取菜单
  async getMenus() {
    const result = await this.net.get('/api/menus');
    if (result) {
      this.menuData = result['data'];
      this.treeData = this.handleMenu(this.menuData);
    }
  }

  async ngOnInit() {
    this.getMenus();
  }
}
